import datetime
import os
import csv

path = "/time/"
#
# files = {
#     "A": "A_time.csv",
#     "B": "B_time.csv",
#     "C": "C_time.csv",
#     "D": "D_time.csv",
#     "S": "S_time.csv",
#     "W": "W_time.csv",
# }
files = {
    "atla": "atla_time.csv",
    "chic": "chic_time.csv",
    "hous": "hous_time.csv",
    "salt": "salt_time.csv",
    "seat": "seat_time.csv",
    "kans": "kans_time.csv",
    "losa": "losa_time.csv",
    "newy32aoa": "newy32aoa_time.csv",
    "wash": "wash_time.csv",
}

# ==============================================================================================
id_actions = {}
device_actions = {}
id_set = set()
device_set = set()


def read_csv_file(device, filename):
    if not os.path.exists:
        print("%s不存在" % filename)
        return

    with open(filename, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        for line in reader:
            a = Action(action_id=line[0], node_index=line[1], action=line[2], time=line[3], device=device)
            id_set.add(a.action_id)
            device_set.add(a.device)

            id_actions.setdefault(a.action_id, dict())
            device_actions.setdefault(a.device, dict())
            id_actions[a.action_id].setdefault(a.action, list())
            device_actions[a.device].setdefault(a.action_id, dict())
            device_actions[a.device][a.action_id].setdefault(a.action, list())

            device_actions[a.device][a.action_id][a.action].append(a)
            id_actions[a.action_id][a.action].append(a)


def read_files():
    for device, filename in files.items():
        read_csv_file(device, os.path.join(path, filename))


def analyse_data():

    for _id in id_set:
        start_action = []
        end_action = []

        actions = []
        start_node = set()
        end_node = set()
        nodes = set()
        devices = dict()

        a_name = ""

        rs_time = dict()

        for d in device_set:
            rs_time.setdefault(d, dict())

        for action_name, action_list in id_actions[_id].items():
            for action in action_list:
                nodes.add(action.get_node_name())
                rs_time[action.device].setdefault(action.node_index, dict())
                devices.setdefault(action.device, dict())
                if action.action.endswith("receive"):
                    rs_time[action.device][action.node_index].setdefault("receive", list())
                    # if rs_time[action.device][action.node_index]["receive"] > action.time:
                    rs_time[action.device][action.node_index]["receive"].append(action.time)

                elif action.action.endswith("send"):
                    rs_time[action.device][action.node_index].setdefault("send", action.time)

            if str(action_name).endswith("start"):
                start_action.extend(iter(action_list))
                for action in action_list:
                    start_node.add(action.get_node_name())
                    a_name = str(action.action)[:-5].strip("* ")
            elif str(action_name).endswith("finish"):
                end_action.extend(iter(action_list))
                for action in action_list:
                    end_node.add(action.get_node_name())

            actions.append(action_name)

        mid_node = nodes.difference(start_node).difference(end_node)

        print("action id:%s" % _id)
        print("action name:%s" % a_name)

        if not start_action:
            print("action %s 没有起始数据" % _id)
            continue

        print("action start node:%s" % start_node)
        print("action mid node:%s" % mid_node)
        print("action end node:%s" % end_node)

        if end_action:
            start_time = min(start_action, key=lambda _a: _a.time)
            end_time = max(end_action, key=lambda _a: _a.time)
            total_time_by_minus = (end_time.time - start_time.time)
            print("start time:%s" % datetime.datetime.fromtimestamp(start_time.time/1000)
                  .strftime("%Y-%m-%d %H:%M:%S.%f"))
            print("end time:%s" % datetime.datetime.fromtimestamp(end_time.time/1000)
                  .strftime("%Y-%m-%d %H:%M:%S.%f"))
            print("total_time: %s ms" % total_time_by_minus)

        for nodes in rs_time.values():
            for node in nodes.values():
                if "receive" in node and "send" in node:
                    r = 0
                    s = node["send"]
                    for t in node["receive"]:
                        if r < t < s:
                            r = t
                    node.setdefault("time", (s-r)/1000000.0)

        for device, nodes in rs_time.items():
            if device not in devices:
                continue
            time_min = 999999999999999999999999999999999999
            time_max = 0
            print("device:%s time:{" % device, end="")
            for node_index, node in nodes.items():
                if "time" in node:
                    print("%s-%s: %sms " % (device, node_index, node["time"]), end="")
                else:
                    time_sum = 0
                    for actions in device_actions[device][_id].values():
                        for action in actions:
                            if action.node_index != node_index:
                                continue
                            if not action.action.startswith("*"):
                                time_sum += action.time
                    print("%s-%s: %sms " % (device, node_index, time_sum), end="")

            print("}")
        print("")


class Action:

    def __init__(self, action_id, node_index, action, time, device):
        self.action = action
        self.action_id = action_id
        self.node_index = node_index
        self.time = float(time)
        self.device = device

    def get_node_name(self) -> str:
        return "%s-%s" % (self.device, self.node_index)
# ==============================================================================================


if __name__ == "__main__":
    read_files()
    analyse_data()
